import express from "express";
import { PrismaClient } from "@prisma/client";
import { CreateId, Time, Check, Result } from "@/utils";

const prisma = new PrismaClient();
const router = express.Router();

/** 创建字典 */
router.post("/create", async (req, res) => {
   const { label, code }: DataDictionary.Create = req.body;
   if (!Check.Required([label, code])) return res.send(Result.Error("参数错误"));
   if (!/^[A-Za-z_]{3,30}$/.test(code)) return res.send(Result.Error("内部名称仅能使用字母和下划线组合"));

   let dic = await prisma.data_dictionary.findMany({ where: { label } });
   if (dic.length > 0) return Result.Error("当前显示名称已存在");
   dic = await prisma.data_dictionary.findMany({ where: { code } });
   if (dic.length > 0) return Result.Error("当前内部名称已存在");

   const { userId } = req;

   // 创建 id
   const id = await CreateId.One("data_dictionary");
   // 插入数据
   await prisma.data_dictionary.create({
      data: {
         id,
         label,
         code,
         created_time: Time.Now(),
         created_by: userId,
         status: "OPEN"
      }
   });

   res.send(Result.OK());
});

/** 编辑字典 */
router.post("/update", async (req, res) => {
   const { id, label, status }: DataDictionary.Update = req.body;
   if (!Check.Required([id, label, status])) return res.send(Result.Error("参数错误"));

   let oldDic = await prisma.data_dictionary.findUnique({ where: { id } });
   if (!oldDic) return Result.Error("当前字典不存在");

   let dic = await prisma.data_dictionary.findFirst({ where: { label } });
   if (!!dic && dic.id != id) return Result.Error("当前显示名称已存在");

   await prisma.data_dictionary.update({
      where: { id },
      data: {
         label: label || oldDic.label,
         status: status || oldDic.status
      }
   });

   res.send(Result.OK());
});

/** 查询字典 */
router.get("/search", async (req, res) => {
   const { label }: DataDictionary.Search = req.query;

   const list = await prisma.data_dictionary.findMany({
      where: {
         AND: [!!label ? { label } : {}]
      },
      select: {
         id: true,
         code: true,
         label: true,
         status: true
      }
   });

   res.send(Result.OK(list));
});

/** 添加字典数据 */
router.post("/valueCreate", async (req, res) => {
   const { dic_id, name }: DataDictionary.ValueCreate = req.body;
   if (!Check.Required([dic_id, name])) return res.send(Result.Error("参数错误"));

   const dic = await prisma.data_dictionary.findUnique({ where: { id: dic_id } });
   if (!dic) return res.send(Result.Error("当前条目不存在"));
   if (!dic.value) dic.value = [];
   if (!Check.IsArray<DataDictionary.Value>(dic.value)) return res.send(Result.Error("当前字典数据错误"));

   const value = dic.value;

   // 查询数据中是否存在相同的名称
   const has = value.find(item => item.name == name);
   if (has) return res.send(Result.Error("当前内部名称已存在"));

   const valueId = await CreateId.OneValueId("data_dictionary", dic_id);
   value.push({
      id: valueId,
      name: name,
      status: "OPEN"
   });

   const { userId } = req;

   await prisma.data_dictionary.update({
      where: { id: dic_id },
      data: {
         value: value,
         old_value: dic.value,
         updated_by: userId,
         updated_time: Time.Now()
      }
   });

   res.send(Result.OK());
});

/** 删除字典数据 */
router.post("/valueDelete", async (req, res) => {
   const { dic_id, value_id }: DataDictionary.ValueDelete = req.body;
   if (!Check.Required([dic_id, value_id])) return res.send(Result.Error("参数错误"));
   const dic = await prisma.data_dictionary.findUnique({ where: { id: dic_id } });
   if (!dic) return res.send(Result.Error("当前条目不存在"));
   if (!dic.value) dic.value = [];
   if (!Check.IsArray<DataDictionary.Value>(dic.value)) return Result.Error("当前字典数据错误");

   const { userId } = req;

   const value = dic.value;

   // 查询数据索引
   const index = value.findIndex(item => item.id == value_id);
   if (index === -1) return res.send(Result.Error("当前条目不存在"));

   // 删除数据
   value.splice(index, 1);

   await prisma.data_dictionary.update({
      where: { id: dic_id },
      data: {
         value: value,
         old_value: dic.value,
         updated_by: userId,
         updated_time: Time.Now()
      }
   });

   res.send(Result.OK());
});

/** 编辑字典数据 */
router.post("/valueUpdate", async (req, res) => {
   const { dic_id, value_id, name, status }: DataDictionary.ValueUpdate = req.body;
   if (!Check.Required([dic_id, value_id, name, status])) return res.send(Result.Error("参数错误"));

   const dic = await prisma.data_dictionary.findUnique({ where: { id: dic_id } });
   if (!dic) return res.send(Result.Error("当前条目不存在"));
   if (!dic.value || !Check.IsArray<DataDictionary.Value>(dic.value)) return res.send(Result.Error("当前字典数据错误"));

   const { userId } = req;

   const value = dic.value;

   // 找到并更新数据
   value.forEach(item => {
      if (item.id == value_id) {
         item.name = name || item.name;
         item.status = status || item.status;
      }
   });

   await prisma.data_dictionary.update({
      where: { id: dic_id },
      data: {
         value: value,
         old_value: dic.value,
         updated_by: userId,
         updated_time: Time.Now()
      }
   });

   res.send(Result.OK());
});

/** 查询字典数据 */
router.get("/valueSearch", async (req, res) => {
   const { dic_id, name, status }: DataDictionary.ValueSearch = req.query as any;
   if (!Check.Required([dic_id])) return res.send(Result.Error("参数错误"));

   const dataDic = await prisma.data_dictionary.findUnique({ where: { id: dic_id } });
   if (!dataDic) return res.send(Result.Error("当前字典不存在"));
   if (!dataDic.value) return res.send(Result.OK([]));
   if (!Check.IsArray<DataDictionary.Value>(dataDic.value)) return res.send(Result.Error("当前字典数据错误"));

   const value = dataDic.value;

   if (value.length == 0) return res.send(Result.OK([]));

   const list = value.filter(item => {
      return (name ? new RegExp(name).test(item.name) : true) && (status ? item.status == status : true);
   });

   return res.send(Result.OK(list));
});

export const dataDictionary = router;
